package com.ruoyi.stream.server.handler;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.stream.framework.constans.StreamProtocolConstants;
import com.ruoyi.stream.framework.core.protocol.StreamAliveRequest;
import com.ruoyi.stream.framework.core.protocol.StreamAliveResponse;
import com.ruoyi.stream.framework.enums.SKARequestOption;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.Arrays;
import java.util.List;

public class SKAResponseDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        try {
            byte[] head = new byte[StreamProtocolConstants.SKA_RESPONSE_MAGIC.length];
            byteBuf.readBytes(head);
            if (!Arrays.equals(head, StreamProtocolConstants.SKA_RESPONSE_MAGIC)) {
                return;
            }
            long length = byteBuf.readLong();
            byte[] bytes = new byte[(int) length];
            byteBuf.readBytes(bytes);
            StreamAliveResponse to = JSON.parseObject(bytes).to(StreamAliveResponse.class);
            list.add(to);

        } catch (Exception e) {
            e.printStackTrace();
            StreamAliveRequest request = new StreamAliveRequest();
            request.setRequestBody(e.getLocalizedMessage());
            request.setOption(SKARequestOption.REFUSE);
            channelHandlerContext.writeAndFlush(request);
        }
    }
}
